package com.cn.tool;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import com.cn.Object.Person;

import java.util.*;

/**
 * @author he_ls
 * @since 2024/6/27 16:40
 **/
public class FastJsonTest {
    public static void main(String[] args) {
        ArrayList<String> toysB = CollectionUtil.newArrayList("霸天虎", "汽车人", "天罡变");
        ArrayList<String> toysG = CollectionUtil.newArrayList("洋娃娃", "汽车人", "小马驹");
        Person p = new Person("小明", 12, "男", "深圳市", new Date(1324234215435L), toysB);
        Person pNull = new Person("小红", null, "女", null, null, toysG);
        Person[] pArray = {p, pNull};

        test4(p);
    }

    static void test4(Person p) {
        System.out.println(p);
//        System.out.println(jsonBytes);
//        System.out.println(new String(jsonBytes));
        String jsonString = JSON.toJSONString(p, "yyyy-MM-dd", JSONWriter.Feature.MapSortField);
        System.out.println(jsonString);

        // 获取key关键字集合
        JSONObject from = JSONObject.from(p);
//        Set<String> strings = from.keySet();
//        Collection<Object> strings = from.values();
//        strings.forEach(System.out::println);

        from.putIfAbsent("name", "雄安");
        from.putIfAbsent("tall", 1.83);

        Set<Map.Entry<String, Object>> entries = from.entrySet();
        for (Map.Entry<String, Object> entry: entries) {
            System.out.println(entry.getKey() + " - " + entry.getValue());
        }
    }

    static void test3(Person person) {
        JSONObject personObject = JSONObject.from(person);
        System.out.println(personObject);

        JSONObject object = new JSONObject();
        Map<String, String> map = new HashMap<>();
        map.put("name", "小绿XX");
        map.put("age", "33");
        map.put("password", "6527367621356");

        personObject.putAll(map);
        System.out.println(personObject);

        Person person1 = personObject.to(Person.class, JSONReader.Feature.AllowUnQuotedFieldNames);
        System.out.println(person1);
    }

    static void test2(Person person) {
        Person person1 = JSON.parseObject(JSON.toJSONString(person), Person.class);
        System.out.println(person1);
    }
    static void test1(Person p) {
        String jsonString = JSON.toJSONString(p);
        System.out.println(jsonString);
        JSONObject jsonObject = JSON.parseObject(jsonString);
        System.out.println(jsonObject);
        System.out.println(jsonObject.get("name"));
        List<String> list = jsonObject.getList("toyList", String.class, JSONReader.Feature.NullOnError);
        System.out.println(list);
    }

}
